//
//  SceneViewController.m
//  OST
//
//  Created by mac on 13-7-15.
//  Copyright (c) 2013年 mac. All rights reserved.
//

#import "SceneViewController.h"
#import "SceneCell.h"
#import "SceneData.h"
#import "SetData.h"
#import "Utitlity.h"
#import "SceneEditViewController.h"
#import "ArmModel.h"
#import "ChangeInfoDialog.h"
#import "TimingSettingViewController.h"


@interface SceneViewController () <UIActionSheetDelegate, UIAlertViewDelegate, SceneArmBaseTableViewCellDelegate, changeDataDicDelegate>

@property (strong, nonatomic) NSArray *deviceList;//用于编辑Scene时可选择添加设备列表
@property (strong, nonatomic) NSArray *armConditionList;
@end

@implementation SceneViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    closeNextPage = YES;
    threadLoadData = NO;
    
    BottomView *bottomView = [self addBottomView];
    bottomView.btn_camera.hidden = NO;
    [bottomView.btn_camera addTarget:self action:@selector(openCamera) forControlEvents:UIControlEventTouchUpInside];
    
    bottomView.btn_all_power.hidden = NO;
    [bottomView.btn_all_power addTarget:self action:@selector(showMenu:) forControlEvents:UIControlEventTouchUpInside];
    
    dataTableView.frame = CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height - bottomView.frame.size.height);
    
    
    //dataTableView.frame = CGRectMake(0, 0, 320, self.view.frame.size.height - 60);
    self.title =@"Scene";
    
    icons = [NSArray arrayWithObjects:@"scene_0",@"scene_1",@"scene_2",@"scene_3", nil];
    
    [self getDeviceList];
    [self refreshData];
    [self reqGetArmConditionList];
}

#pragma mark - UITableView Delegate
-(CGFloat)rowHeight
{
    return 76;
}

- (UITableViewCell *)cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	NSUInteger row=[indexPath row];
    static NSString *SceneCellIdentifier = @"SceneCellIdentifier";
    SceneCell *cell = (SceneCell*)[dataTableView dequeueReusableCellWithIdentifier:SceneCellIdentifier];
    if (cell==nil) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"SceneCell" owner:self options:nil]lastObject];
        [cell initView];
        cell.icon.image = [UIImage imageNamed:[icons objectAtIndex:row%[icons count]]];
        cell.delegate = self;
    }
    NSDictionary *rowData = [self.rows objectAtIndex:row];
    cell.data = rowData;
    cell.labelName.text = [rowData objectForKey:@"label"];
    
    [cell editButtonAddTarget:self action:@selector(showSceneEditVC:)];
    
    [cell activateButtonAddTarget:self action:@selector(activateScene:)];
    return cell;
}

-(void)didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //NSUInteger row=[indexPath row];
    //NSDictionary *rowData = [rows objectAtIndex:row];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary *rowData = self.rows[indexPath.row];
    [self deleteScene:rowData];
}

#pragma mark - 
-(NSArray *)loadPageData:(int)page
{
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl) {
    
    [activity startAnimating];

    NSString *urlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Scene.cgi?action=do_list", ipUrl];
    
    [Utitlity commonHTTPMethod:urlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [activity stopAnimating];
        
        if (!responseObject) return;
        NSDictionary *retJsonData = responseObject;
        if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
            
            NSMutableArray *resultItem = [[NSMutableArray alloc] init];
            NSArray *devList = [retJsonData objectForKey:@"data"];
            for (NSDictionary *dict in devList)
            {
                [resultItem addObject:dict];
            }
            //self.rows = result;
            [super doneLoadingTableViewData:resultItem];
            //[dataTableView reloadData];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [activity stopAnimating];
        NSLog(@"error:%@",error);
    }];
    
    }
    
    return nil;
}

- (void)getDeviceList {
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl) {
        
    NSString *loadStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Get.cgi?Get=1", ipUrl];
    [Utitlity commonHTTPMethod:loadStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
        
        NSMutableArray *resultItem = [[NSMutableArray alloc] init];
        NSArray *devList = responseObject[@"data"];
        for (NSDictionary *item in devList) {
            
            NSInteger deviceType = [[item objectForKey:@"DeviceType"] integerValue];
            if (deviceType != SceneDeviceTypeBinarySensor && deviceType != SceneDeviceTypeMultilevelSensor)
            {//情景不需要Sensor
                [resultItem addObject:item];
            }
        }
        
        self.deviceList = resultItem;
        NSLog(@"resultItem:%@",responseObject);
        
    }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"error:%@",error);
    }];
        
    }
}

- (void)reqGetArmConditionList {
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl) {
        
        NSString *loadStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Cond.cgi?action=do_list", ipUrl];
        [Utitlity commonHTTPMethod:loadStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
            
            if (!responseObject || ![responseObject isKindOfClass:[NSDictionary class]]) return;
            
            NSMutableArray *list = [NSMutableArray arrayWithCapacity:10];
            NSArray *devList = responseObject[@"data"];
            for (NSDictionary *item in devList) {
                
                ArmModel *data = [[ArmModel alloc] initWithJSON:item];
                [list addObject:data];
            }
            self.armConditionList = list;
            DLog(@"resultItem:%@",responseObject);
            
        }failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"error:%@",error);
        }];
    }
}

- (void)newSceneRequest:(NSString *)sceneName {
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl) {

    [activity startAnimating];

    ASIFormDataRequest *formDataRequest = [ASIFormDataRequest requestWithURL:nil];
    NSString *encodedSceneName = [formDataRequest encodeURL:sceneName];
    
    NSString *urlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Scene.cgi?action=do_create&label=%@", ipUrl, encodedSceneName];
    
    [Utitlity commonHTTPMethod:urlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [activity stopAnimating];
        
        if (!responseObject) return;
        NSDictionary *retJsonData = responseObject;
        if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
            
            //                NSMutableArray *result = [NSMutableArray array];
            NSDictionary *newScene = [retJsonData objectForKey:@"data"];
           
            [self.rows addObject:newScene];
            [dataTableView reloadData];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [activity stopAnimating];
        NSLog(@"error:%@",error);
    }];
        
    }
}

- (void)deleteScene:(NSDictionary *)sceneData {
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl) {

    [activity startAnimating];

    NSString *urlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Scene.cgi?action=do_destroy&scene=%@", ipUrl, sceneData[@"scene"]];
    
    [Utitlity commonHTTPMethod:urlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [activity stopAnimating];
        
        if (!responseObject) return;
        NSDictionary *retJsonData = responseObject;
        if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
            
            [self.rows removeObject:sceneData];
            [dataTableView reloadData];
        }
        [dataTableView setEditing:!dataTableView.editing animated:YES];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [activity stopAnimating];
        NSLog(@"error:%@",error);
        [dataTableView setEditing:!dataTableView.editing animated:YES];
    }];
    }
}

//!请求启动情景
- (void)reqActivateScene:(NSDictionary *)sceneData withActivateBtn:(UIButton *)btn {
    
    ipUrl = [Utitlity judgeipUrl];
    if (ipUrl) {

    [activity startAnimating];
    
    NSString *urlStr = [NSString stringWithFormat:@"http://%@/cgi-bin/Scene.cgi?action=do_activate&scene=%@", ipUrl, sceneData[@"scene"]];
    
    [Utitlity commonHTTPMethod:urlStr responseType:jsonType success:^(AFHTTPRequestOperation *operation, id responseObject) {
        [activity stopAnimating];
        
        if (!responseObject) return;
        NSDictionary *retJsonData = responseObject;
        if ( [[[retJsonData objectForKey:@"state"] lowercaseString] isEqualToString:@"success"] ) {
            
            [btn setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                
                [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
                
            });

            
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [activity stopAnimating];
        NSLog(@"error:%@",error);
        [dataTableView setEditing:!dataTableView.editing animated:YES];
    }];
    }
}

#pragma mark - UIButton
- (void)openCamera:(id)sender {
    
    
}

- (void)showMenu:(UIButton *)sender {
    
    UIActionSheet *menu = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:@"添加情景" otherButtonTitles:@"删除情景", nil];
    [menu showFromRect:sender.frame inView:self.view animated:YES];
}

#pragma mark - UIActionSheet
- (void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    
    switch (buttonIndex) {
        case 0:
        {
            UIAlertView *addScenePrompt = [[UIAlertView alloc] initWithTitle:@"新增情景" message:nil delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
            addScenePrompt.alertViewStyle = UIAlertViewStylePlainTextInput;
            UITextField *tf = [addScenePrompt textFieldAtIndex:0];
            tf.placeholder = @"名称";
            [addScenePrompt show];
            break;
        }

        case 1:
        {
            [dataTableView setEditing:!dataTableView.editing animated:YES];
            break;
        }
            
        default:
            break;
    }
}

#pragma mark - UIButton
- (void)showSceneEditVC:(UIButton *)sender {
    
    CGRect btnRect = sender.frame;
    CGPoint p = [sender convertPoint:btnRect.origin toView:dataTableView];
    CGPoint cellP = CGPointMake(0, p.y);
    NSIndexPath *indexPath = [dataTableView indexPathForRowAtPoint:cellP];
    if (indexPath.row < self.rows.count) {
        
        SceneEditViewController *vc = [[SceneEditViewController alloc] initWithNibName:@"SceneEditViewController" bundle:nil];
        vc.sceneData = self.rows[indexPath.row];
        vc.armConditionList = self.armConditionList;
        [vc setSelectDeviceList:self.deviceList];
        [self.navigationController pushViewController:vc animated:YES];
    }
}

- (IBAction)activateScene:(UIButton *)sender {
    
    UIView *cellContentView = sender.superview;
    if (cellContentView) {
        id cell = cellContentView.superview.superview;
        if ([cell isMemberOfClass:[SceneCell class]]) {
            SceneCell *scenCell = (SceneCell *)cell;
            [self reqActivateScene:scenCell.data withActivateBtn:sender];
        }
    }
}

#pragma mark - UIAlertView
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 1) {
        
        NSString *txt = [alertView textFieldAtIndex:0].text;
        [self performSelectorOnMainThread:@selector(newSceneRequest:) withObject:txt waitUntilDone:NO];

    }
}

#pragma mark - SceneCell Delegate
- (void)changeInfo:(NSDictionary *)data cell:(SceneArmBaseTableViewCell *)cell {
    
    ChangeInfoDialog  *yijianview = [[[NSBundle mainBundle] loadNibNamed:@"ChangeInfoDialog" owner:self options:nil]lastObject];
    yijianview.delegate = self;
    [yijianview initView];
    [yijianview setSceneArmDData:data cell:cell];
    [yijianview pageStart];
}


@end
